package com.dayuanit.dy8.atm.springbootatm.controller;

import com.dayuanit.dy8.atm.config.testautoconfig.service.AtmConfigService;
import com.dayuanit.dy8.atm.springbootatm.dto.ResponseDTO;
import com.dayuanit.dy8.atm.springbootatm.entity.User;
import com.dayuanit.dy8.atm.springbootatm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.UUID;

@Controller
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private AtmConfigService atmConfigService;

    @RequestMapping("/user/upload")
    public String upload(@RequestParam("upfile") MultipartFile file, String note, HttpServletRequest request) {
        System.out.println("note=" + note);
        if (file.isEmpty()) {
            return "xxx";
        }

        System.out.println("URI=" + request.getRequestURI());// /user/upload.do
        System.out.println("URL=" + request.getRequestURL());// http://127.0.0.1:8088/user/upload.do
        System.out.println("cp=" + request.getContextPath());// 空
        System.out.println("sp=" + request.getServletPath());// /user/upload.do

        System.out.println(">>>>>>>RealPath=" + request.getSession().getServletContext().getRealPath("/"));



        try {
//            String filepath = WebUtils.getRealPath(request.getServletContext(), "/WEB-INF/upload/" + UUID.randomUUID() + ".jpg");
            String filepath = "/" +  UUID.randomUUID() + ".jpg";
            System.out.println("filepath=" + filepath);
            int length = file.getBytes().length;
            byte[] fileData = file.getBytes();
            final FileOutputStream fos = new FileOutputStream(filepath);
            fos.write(fileData);
            fos.flush();
            fos.close();

            System.out.println("文件大小=" + length);
            System.out.println("filename=" + file.getName());
        } catch (Exception e) {
            e.printStackTrace();
        }


        return "";
    }

    @RequestMapping("/user/showAvatar")
    public void showAvatar(HttpServletResponse response, HttpSession session) {
        String fileName =  getUserId(session) + ".jpg";
        try(OutputStream os = response.getOutputStream();
            InputStream is = new FileInputStream(avatarFilePath + fileName)) {
            int data = -1;
            while (-1 != (data = is.read())) {
                os.write(data);
                os.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/user/uploadAvatar")
    public void uploadAvatar(@RequestParam("avatar") MultipartFile avatar, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        try {
            String filepath = super.avatarFilePath +  getUserId(session) + ".jpg";
            avatar.transferTo(new File(filepath));
            try(OutputStream os = response.getOutputStream();) {
                os.write("<script>parent.showAvatar('/user/showAvatar')</script>".getBytes());
                os.flush();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @RequestMapping("/login")
    @ResponseBody
    public ResponseDTO login(String username, String pwd, String captcha, HttpSession session) {

        logger.info("login username={}, pwd={},captcha={}", username, pwd, captcha);

        Object obj = session.getAttribute("captcha");
        if (null == obj) {
            return ResponseDTO.fail("请刷新页面");
        }

        if (!obj.toString().equalsIgnoreCase(captcha)) {
            session.removeAttribute("captcha");
            return ResponseDTO.fail("验证码错误");
        }

        int a=0;
        int b=1;


        User user = userService.login(username, pwd);
        session.setAttribute("loginUser", user);
        return ResponseDTO.success();
    }

    @RequestMapping("/regist")
    @ResponseBody
    public ResponseDTO regist(String username, String pwd, String confirmPwd) {
        atmConfigService.say();
        userService.regist(username, pwd, confirmPwd);
        return ResponseDTO.success();
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session, HttpServletResponse response) {
        session.removeAttribute("loginUser");
        session.invalidate();
        return "redirect:/";
    }

}
